package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;


    @Override// 员工登录
    public ResultInfo login(String username, String password) {// password = 123456
        //根据username查询mapper
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("用户不存在");
        }
        //密码比较
        //2.1将前端密码MD5加密
        String md5 = SecureUtil.md5(password);
        //跟数据库比较
        if (!md5.equals(employee.getPassword())) {
            return ResultInfo.error("密码错误");
        }
        //判断此账号是否禁用
        if (employee.getStatus() == 0) {
            return ResultInfo.error("此账号被禁用");
        }
        return ResultInfo.success(employee);
    }

    @Override//员工列表
    public List<Employee> find(String name) {
        return employeeMapper.find(name);
    }

    @Override//新增员工
    public void save(Employee employee) {//接受请求参数
        //1.补全员工信息
        //1.1雪花算法生成id
        long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);
        //1-2初始密码
        String md5 = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(md5);
        //1-3员工状态
        employee.setStatus(1);
      // //1-4创建更新时间  TODO
      // employee.setUpdateTime(new Date());
      // employee.setCreateTime(new Date());
      // //1-5
      // employee.setCreateUser(1L);
      // employee.setUpdateUser(1L);
        //调用mapper新增
        employeeMapper.insert(employee);

    }

    @Override // 回显员工
    public Employee findById(Long id) {
        return employeeMapper.findbyid(id);
    }

    @Override//修改员工
    public void update(Employee employee) {
        //补全信息
        //1-1
        //employee.setUpdateUser(1L);
        //employee.setUpdateTime(new Date());
        //调用mapper修改
        employeeMapper.updateById(employee);
    }

}
